package com.wsjj.gmall.util;

import com.google.common.base.CaseFormat;
import com.wsjj.gmall.constant.Constant;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class JdbcUtil {
//    创建连接

    /**
     * 返回的是连接对象
     * @return
     * @throws Exception
     */
    public static Connection createMysqlConnection() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER_NAME, Constant.MYSQL_PASSWORD);
        return connection;

    }
//    关闭连接

    /**
     *
     * @param conn  传入的mysql连接对象
     * @throws SQLException
     */
    public static void closeMysqlConnection(Connection conn) throws SQLException {
        if(conn != null && conn.isClosed()){
            conn.close();
        }
    }
//    查询表中的所有数据

    /**
     *
     * @param sql  传入的sql
     * @param clazz     传入返回对象类型
     * @param isUnderLineToCamel       是否驼峰命名
     * @return  返回List集合，集中中的对象需要传入进去
     * @param <T>   要返回List中的对象
     */
    public static <T>List<T> selectList(Connection conn,String sql,Class<T> clazz,boolean... isUnderLineToCamel) throws Exception {
        boolean defaultIsUToC = false;
        if (isUnderLineToCamel.length > 0) {
             defaultIsUToC = isUnderLineToCamel[0];
        }
//      编译sql
        PreparedStatement statement = conn.prepareStatement(sql);
//        执行sql
        ResultSet resultSet = statement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();

        List<T> list = new ArrayList<>();

        while (resultSet.next()){
            T t = clazz.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(i);



                if(defaultIsUToC){
                    columnName= CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName);
                }

                BeanUtils.setProperty(t,columnName,object);
            }
            list.add(t);
        }
        return list;


    }


}
